<template>
	<div>
		<div style="width: 100%;height: 5vh; position: fixed;top: 0;z-index: 5;">
			<van-nav-bar title="消息">
				<template #right>
					<van-icon name="search" size="18" />
				</template>

			</van-nav-bar>
		</div>
		<div style="margin-top: 5vh;">
			<van-pull-refresh v-model="messageListRefreshing" @refresh="reflashMessage">
				<div style="height: 90vh;">
					<div v-for="(msg, index) in messageList" :key="index">
						<MessageCell :data="msg" :openPage="openChatPage"></MessageCell>
					</div>
				</div>
			</van-pull-refresh>

		</div>
		
		<div>
			<van-popup :before-close="beforeChatPageClose" v-model:show="showChatPage" position="right" style="width: 100%;height:100%;background-color: #FAFAFA" closeable
				close-icon="arrow-left" close-icon-position="top-left" >
				<ChatPage ref="chatPage"></ChatPage>
			</van-popup>
		</div>
	</div>
</template>

<script>
	import ChatPage from './ChatPage.vue'
	import MessageCell from '@/components/units/MessageCell.vue';
	import {
		showNotify
	} from 'vant';
	import url from '@/assets/url.json';
	import {
		ref
	} from 'vue';

	export default {
		components: {
			MessageCell,
			ChatPage
		},
		mounted() {
				this.getMassage();
		},
		data() {
			return {
				showChatPage:false,
				messageListRefreshing:false,
				messageList: [
				],
				chatPageData: {
					chatPageList:[]
				},
			}
		},
		methods:{
			getMassage(){
				this.$axios({
					url: url.ip + '/api-user' + '/chat/getChatList',
					method: 'GET',
					params:{
						id:this.$cookies.get("userId")
					},
					headers: {
						token: this.$cookies.get('token')
					}
				}).then((res)=>{
					if(res.data.code!=0){
						showNotify({
							type: 'danger',
							message: res.data.message
						});
					}else{
						console.log(res.data)
						let chatList = res.data.data;
						for(let chat of chatList){
							if(chat.guid===this.$cookies.get("userId")){
								continue;
							}
							this.messageList.push({
							id: chat.guid,
							userName: chat.guser.userName,
							context: "",
							headImgSrc: url.ip+'/'+chat.guser.headImgSrc
						})
						}
					}
				})
			},
			reflashMessage(){
				console.log("获取消息列表");
				this.messageList = [];
				this.getMassage();
				setTimeout(()=>{
					this.messageListRefreshing=false
				},1000)
			},
			openChatPage(data){
			
				this.chatPageData=data;
				this.showChatPage=true;
				setTimeout(()=>{
					if((typeof this.$refs.chatPage)!=='undefined'){
						this.$refs.chatPage.getData(this.$cookies.get("userId"),data.id,data.userName);
						this.$refs.chatPage.showPage();
					}
				},1000)
				
			},
			beforeChatPageClose(){
				this.$refs.chatPage.beforePageClose();
				return true;
			}
		},

		setup() {
			const list = ref([]);
			const loading = ref(false);
			const finished = ref(false);


			return {
				list,
				loading,
				finished,
			};
		},
	};
</script>

<style>
</style>